Lecture : Hello Python!


  • [RQ-1] : Which of the following statements is correct?

    Ans: The Ipython Shell is typically used to work with Python interactively.

  • [RQ-2] : Which file extension is used for Python script files?**

    Ans: .py

  • [RQ-3] : You need to print the result of adding 3 and 4 inside a script. Which line of code should you write in the script?

    Ans: print(int x + int y)


Lab : Hello Python!


Objective :

  • How to work with Ipython shell.
  • Writing python scripts.

The Python Interface -- 100xp, Status : Earned


In [1]:
# working with print function
print(5 / 8)

# Add another print function on new line
print(7 + 10)


0.625
17

When to use python? -- 50xp, Status : Earned


Python is a pretty versatile language. For what applications can you use Python?

Ans: All of the above


Any comments? -- 100xp, Satatus : Earned


  • We can add comments to python scripts.

  • Comments are short snippets of plain english, to help you and others understand what the code is about.

  • To add a comment, use '#'tag, insert it at the front of the text.

  • Comments have idle state, i.e. they don't affect the code results.

  • Comments are ignored by the python interpretor.



In [2]:
# Just testing division
print(5 / 8)

# Additon works too ( added comment here )
print(7 + 10)


0.625
17

Python as a calculator -- 100xp, Status : Earned


Python is perfectly suited to do basic calculations. Apart from addition, subtraction, multiplication and division, there is also support for more advanced operations such as:

  • Exponentiation:. This operator raises the number to its left to the power of the number to its right: for example 42 will give 16.
  • Modulo: %. It returns the remainder of the division of the number to the left by the number on its right, for example 18 % 7 equals 4.


In [9]:
"""Suppose you have $100, which you can invest with a 10% return each year. After one year, it's 
100 x 1.1 = 110 dollars, and after two years it's 100 x 1.1 x 1.1 = 121.

Add code to calculate how much money you end up with after 7 years"""

print(5 + 5)
print(5 - 5)

# Multiplication and division
print(3 * 5)
print(10 / 2)

# Exponentiation
print(4 ** 2)

# Modulo
print(18 % 7)

# How much is your $100 worth after 7 years?
# first try was unsuccesful, so used the only two things * and ** operators.
print ( 100 * ( 1.1 ** 7 ) )


10
0
15
5.0
16
4
194.87171000000012

Lecture : Variables and Types


  • [RQ1] : Which line of code creates a variable x with the value '15'?

    Ans: x = 15 ( inline code used ).

  • [RQ2] : What is the value of the variable z after executing these commands?

      x = 15
      y = 7
      z = x + y + 1

    Ans: 13

  • [RQ3] : You execute the following two lines of Python code:

      x = "test"
      y = False

    Ans: x is a string, and y is a boolean.


Lab : Variables and Types


Objective:

  • Creating Variables.
  • Performing Calculations on them.
  • Understand different data types that python offers.

  • Variable Assignment, earned credit : 100xp
  • Calculations with variables, earned credit : 100xp
  • Other variable types, earned credit : 100xp
  • Guess the type, earned credit : 50xp
  • Operations with the other types, earned credit : 100xp
  • Type conversion, earned credit : 100xp
  • Can Python handle everything?, earned credit : 50xp

1. Variable Assignment

In Python, a variable allows you to refer to a value with a name. To create a variable use =, like this example:

x = 5

You can now use the name of this varibale x, instead of the actual value, 5.


In [4]:
"""
    Instructions :
    
    * Create a variable savings with the value 100.
    
    * Check out this variable by typing 'print( savings )` in the script.
    
"""

# Create a variable savings
savings = 100

# Print out savings
print("savings: ", savings )


savings:  100

2. Calculations with variables

Remember how you calculated the money you ended up with after 7 years of investing $100? You did something like this:

100 * 1.10 ** 7

Instead of calculating with the actual values, you can use variables instead. The savings variable you've created in the previous exercise represents the $100 you started with. It's up to you to create a new variable to represent 1.10 and then redo the calculations!


In [4]:
"""
    Instructions : 
    
    * Create a variable factor, equal to 1.10.
    
    * Use savings and factor to calculate the amount of money, 
      you end up with after 7 years. Store the result in a new variable,
      result.
      
"""

# Create a variable savings
savings = 100

# Create a variable factor
factor = 1.10

# Calculate result
result =  savings * ( factor ** 7 )

# Print out result
print( result )


194.87171000000012

3. Other variable types

In the previous exercise, you worked with two Python data types:

  • int, or integer: a number without a fractional part. savings, with the value 100, is an example of an integer.

  • float, or floating point: a number that has both an integer and fractional part, separated by a point. factor, with the value 1.10, is an example of a float.

Next to numerical data types, there are two other very common data types:

  • str, or string: a type to represent text. You can use single or double quotes to build a string.

  • bool, or boolean: a type to represent logical values. Can only be True or False.



In [6]:
"""
Instructions : 

    * Create a new string, 'desc', with the value "compound interest".
    
    * Create a new boolean, 'profitable', with the value 'True'.
    
"""

# Create a variable desc
desc = "compound interest"

# Create a variable profitable
profitable = True

4. Guess the type

To find out the type of a value or a variable that refers to that value, you can use the type() function. Suppose you've defined a variable a, but you forgot the type of this variable. To determine the type of `a, simply execute:

type(a)


In [10]:
a = 10.21
b = "Python's fun!"
c = False

# Check there types:

type(a)


Out[10]:
float

In [11]:
type(b)


Out[11]:
str

In [12]:
type(c)


Out[12]:
bool

5. Operations with other types

Different types behave differently in python,

  • Sum of two or more strings will be a "concatenation" ( pasting ) of two or more string together.
  • Sum of two or more int is an int
  • Sum of two or more floats is a float, except some special situations.
  • Sum of two or more bool is a bool.

In [15]:
"""
Instructions :

    + Calculate the product of 'savings' and 'factor'.
        - Store the result in 'yearl'.
    
    + What do you think the resulting type will be?
        - Find out by printing out the type of 'yearl'
        
    + Calculate the sum of 'desc' and 'desc'.
        - Store the result in new variable 'doubledesc'.
        
    + Print out 'doubledesc'.
        - Did you expect this?
"""

# Several variables to experiment with
savings = 100
factor = 1.1
desc = "compound interest"

# Assign product of factor and savings to year1
year1 = savings * factor

# Print the type of year1
print( type( yearl ) )

# Assign sum of desc and desc to doubledesc
doubledesc = desc + desc

# Print out doubledesc
print( doubledesc )


<class 'float'>
compound interestcompound interest

6. Type conversion

Using the + operator to paste together two strings can be very useful in building custom messages.

Suppose for example that you've calculated the return of your investment, and want to summarize the results in a string. Assuming the floats savings and result are defined, you can try something like this:

print("I started with $" + savings + " and now have $" + result + ". Awesome!")

note: But we cannot sum strings and floats, so above code will return an error.

To fix the error:

  • Need to explicitly convert the types of your variables.

  • Use a str() to convert a value into a string.

  • Similerly, use int(), float and bool() for desired conversion types.


In [17]:
"""
Instructions: 

    + First run the code, and identify the errors.
    
    + Next, fix those errors by appropritate type conversion functions.
    
    + Convert variable 'pi_string' --> 'float', as a new variable 'pi_float'.
    
"""
# Definition of savings and result
savings = 100
result = 100 * 1.10 ** 7

# Fix the printout
print("I started with $" + savings + " and now have $" + result + ". Awesome!")

# Definition of pi_string
pi_string = "3.1415926"

# Convert pi_string into float: pi_float


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-cfbf2df7fcc1> in <module>()
     14 
     15 # Fix the printout
---> 16 print("I started with $" + savings + " and now have $" + result + ". Awesome!")
     17 
     18 # Definition of pi_string

TypeError: Can't convert 'int' object to str implicitly

In [20]:
# Fixed code
# Definition of savings and result
savings = 100
result = 100 * 1.10 ** 7

# Fix the printout
print("I started with $" + str( savings ) + " and now have $" + str( result ) + ". Awesome!")

# Definition of pi_string
pi_string = "3.1415926"

# Convert pi_string into float: pi_float
pi_float = float(pi_string)


I started with $100 and now have $194.87171000000012. Awesome!

7. Can Python handle everything?

Following are some code snipptes, try to find which one is correct:

  • "I can add integers, like" + str(5) + "to strings."
  • "I said " + ("Hey " * 2) + "Hey!"
  • "The correct answer to this multiple choice exercise is answer number " + 2
  • True + False


In [1]:
print( "I can add integers, like " + str(5) + " to strings." )

print( "I said " + ("Hey " * 2) + "Hey!" )

# Error
("The correct answer to this multiple choice exercise is answer number " + 2)


I can add integers, like 5 to strings.
I said Hey Hey Hey!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-dec7ca664aa4> in <module>()
      5 
      6 # Error
----> 7 ("The correct answer to this multiple choice exercise is answer number " + 2)
      8 
      9 print( True + False )

TypeError: Can't convert 'int' object to str implicitly

In [3]:
print( True + False )


1